#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

enum class Status
{
    NEW,          // 新建状态
    CONNECTING,   // 正在连接，仅方便查看conn状态
    CONNECTED,    // 连接成功
    DISCONNECTED, // 连接失败或重连失败
    CLOSED        // 经过重连后还是失败。
};

enum ExitCode
{
    USAGE_ERR = 1,
    SOCKET_ERR,
};

const static int defaultsockfd = -1;
const static int defaultretryinterval = 1;
const static int defaultmaxretries = 5;

class ClientConnection
{
public:
    ClientConnection(const std::string &serverip, uint16_t serverport)
        : _sockfd(defaultsockfd), _serverip(serverip), _serverport(serverport), _status(Status::NEW), _retry_interval(defaultretryinterval), _max_retries(defaultmaxretries)
    {
    }

    void Connect()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "create socket error" << std::endl;
            exit(SOCKET_ERR);
        }

        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        inet_pton(AF_INET, _serverip.c_str(), &server.sin_addr);

        int n = connect(_sockfd, (const sockaddr*)&server, sizeof(server));
        if (n < 0)
        {
            Disconnect();  // 关闭sockfd
            _status = Status::DISCONNECTED; // 连接失败
            return;
        }
        // 连接成功
        _status = Status::CONNECTED;
    }

    void Reconnect()
    {
        _status = Status::CONNECTING;
        int count = 0;
        while (count < _max_retries)
        {
            // _status = Status::CONNECTING;
            Connect();
            if (_status == Status::CONNECTED)
                return;
            ++count;
            std::cout << "正在重连..., 重连次数: " << count << std::endl;
            sleep(_retry_interval);
        }
        _status = Status::CLOSED;
        std::cout << "重连失败,请检查你的网络..." << std:: endl;
    }

    void Process()
    {
        while (true)
        {
            std::string message = "hello server";
            int n = send(_sockfd, message.c_str(), message.size(), 0);
            if (n > 0)
            {
                char buffer[1024];
                int m = recv(_sockfd, buffer, sizeof(buffer)-1, 0);
                if (m > 0)
                {
                    buffer[m] = 0;
                    std::cout << buffer << std::endl;
                }
                else // 读取失败或断开连接
                {
                    _status = Status::DISCONNECTED;
                    break;
                }
            }
            else
            {
                std::cerr << "send error" << std::endl;
                _status = Status::CLOSED;
                // _status = Status::DISCONNECTED;
                break;
            }
            sleep(1);
        }
    }

    void Disconnect()
    {
        if (_sockfd > defaultsockfd)
        {
            close(_sockfd);
            _sockfd = -1;
        }
    }

    Status GetStatus() { return _status; }

    ~ClientConnection()
    {
    }

private:
    int _sockfd;
    std::string _serverip; // 服务器IP
    uint16_t _serverport;  // 服务器端口
    Status _status;        // 当前连接状态
    int _retry_interval;   // 重连时间间隔
    int _max_retries;      // 最大重连次数
};

class TcpClient
{
public:
    TcpClient(const std::string &serverip, uint16_t serverport)
        : _connection(serverip, serverport)
    {
    }

    void Execute()
    {
        while (true)
        {
            switch (_connection.GetStatus())
            {
            case Status::NEW:
                _connection.Connect();
                break;
            case Status::CONNECTED:
                _connection.Process();
                break;
            case Status::DISCONNECTED:
                _connection.Reconnect();
                break;
            case Status::CLOSED:
                _connection.Disconnect();
                return;
            default:
                break;
            }
        }
    }

    ~TcpClient()
    {
    }

private:
    ClientConnection _connection;
};

// ./client_tcp serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        exit(USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    TcpClient client(serverip, serverport);
    client.Execute();
    return 0;
}